

#include "adc.h"

// 总时间  M*N*21us
#define N 200 // 采样次数

uint16_t resultsBuffer[5];
/*
函数功能：初始化五路ADC通道转换
输入：无
输出：无
备注：
        AD9         P4.4
        AD10        P4.3
        AD11        P4.2
        AD12        P4.1
        AD13        P1.0
*/
void ADC_Config(void)
{
    /* 启用浮点运算的FPU */
    FPU_enableModule();
    FPU_enableLazyStacking();

    /* Initializing ADC (MCLK/1/1) */
    ADC14_enableModule();                                                                   // 使能ADC14模块
    ADC14_initModule(ADC_CLOCKSOURCE_SMCLK, ADC_PREDIVIDER_4, ADC_DIVIDER_5, ADC_MAPINTCH0); // 初始化ADC 时钟 分频  通道 2.4MHz

    GPIO_setAsPeripheralModuleFunctionInputPin(GPIO_PORT_P4, GPIO_PIN0 | GPIO_PIN1 | GPIO_PIN2 | GPIO_PIN3 | GPIO_PIN4, GPIO_TERTIARY_MODULE_FUNCTION); //
    ADC14_configureMultiSequenceMode(ADC_MEM9, ADC_MEM13, true);
    ADC14_configureConversionMemory(ADC_MEM9, ADC_VREFPOS_INTBUF_VREFNEG_VSS, ADC_INPUT_A9, false);
    ADC14_configureConversionMemory(ADC_MEM10, ADC_VREFPOS_INTBUF_VREFNEG_VSS, ADC_INPUT_A10, false);
    ADC14_configureConversionMemory(ADC_MEM11, ADC_VREFPOS_INTBUF_VREFNEG_VSS, ADC_INPUT_A11, false);
    ADC14_configureConversionMemory(ADC_MEM12, ADC_VREFPOS_INTBUF_VREFNEG_VSS, ADC_INPUT_A12, false);
    ADC14_configureConversionMemory(ADC_MEM13, ADC_VREFPOS_INTBUF_VREFNEG_VSS, ADC_INPUT_A13, false);

    ADC14_clearInterruptFlag(ADC_INT13);
    ADC14_enableInterrupt(ADC_INT13);

    /* Enabling Interrupts */
    Interrupt_enableInterrupt(INT_ADC14); // ADC模块的中断
    Interrupt_enableMaster();

    /* Setting up the sample timer to automatically step through the sequence
     * convert.
     */
    ADC14_enableSampleTimer(ADC_AUTOMATIC_ITERATION); // 自动触发

    /* Triggering the start of the sample */
    ADC14_enableConversion();        // 使能开始转换(触发后 自动ADC上电)
    ADC14_toggleConversionTrigger(); // 开启第一次软件触发
}
/*
函数功能：ADC14中断服务函数
输入：无
输出：无
备注：用于ADC的读取
*/
void ADC14_IRQHandler(void)
{
    uint_fast64_t status = ADC14_getEnabledInterruptStatus();

    //    MAP_ADC14_getMultiSequenceResult(resultsBuffer);
    if (status & ADC_INT13)
    {
        resultsBuffer[0] = ADC14_getResult(ADC_MEM9);  // AD9          P4.4
        resultsBuffer[1] = ADC14_getResult(ADC_MEM10); // AD10         P4.3
        resultsBuffer[2] = ADC14_getResult(ADC_MEM11); // AD11         P4.2
        resultsBuffer[3] = ADC14_getResult(ADC_MEM12); // AD12         P4.1
        resultsBuffer[4] = ADC14_getResult(ADC_MEM13); // AD13      P4.0
        ADC14_clearInterruptFlag(status);
    }

    // for (i = 0; i < 5; i++)
    //     OLED_ShowNum(2, 4 + i, resultsBuffer[i], 4, 8);
}
/*
函数功能：返回一个ADC转换完成的数组变量
输入：无
输出：uint16_t*   数组指针
备注：返回值必须赋给一个uint16_t* 的指针变量
*/
uint16_t *ADC_Return_value(void)
{
    return resultsBuffer;
}
